package com.hexb.core.mybatis

import com.hexb.core.model.EnumValueTypeHandler
import com.hexb.core.model.ValueEnum
import com.hexb.core.properties.ProjectProperties
import com.hexb.core.scanner.BaseMapperScanner
import com.hexb.core.utils.ValueEnumUtils
import org.apache.ibatis.session.Configuration
import org.apache.ibatis.type.EnumOrdinalTypeHandler
import org.apache.log4j.Logger
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer
import org.springframework.beans.factory.annotation.Autowired

/**
 * @Package : com.hexb.mt.config
 * @Author : hexb 
 * @Date : 2018-08-10 14:06
 */

class BaseMapperConfiguration implements ConfigurationCustomizer {

    static final Logger logger = Logger.getLogger(BaseMapperConfiguration.class)

    private String scanPackages
    private MapStatementBuilder mapStatementBuilder
    static ProjectProperties projectProperties


    BaseMapperConfiguration(String scanPackages, MapStatementBuilder mapStatementBuilder) {
        this.scanPackages = scanPackages
        this.mapStatementBuilder = mapStatementBuilder
    }

    @Override
    void customize(Configuration configuration) {
        configuration.typeHandlerRegistry.register(ValueEnum.class, new EnumValueTypeHandler())
        new BaseMapperScanner().scanner(scanPackages).each {
            try {
                def sqlEntry = SqlEntryBuilder.toSqlBuildEntry(it, configuration)
                mapStatementBuilder.create(sqlEntry, configuration).each { ms ->
                    configuration.addMappedStatement(ms)
                }
            } catch (e) {
                logger.error(e)
            }
        }
    }

    @Autowired
    void setProjectProperties(ProjectProperties pp){
        BaseMapperConfiguration.projectProperties = pp
    }
}
